<template>
  <div class="app-container">
    <el-row :gutter="80">
      <el-col :span="12">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="任务名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入任务名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:respinfo:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:respinfo:remove']"
            >删除</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="warning"-->
<!--              plain-->
<!--              icon="el-icon-download"-->
<!--              size="mini"-->
<!--              @click="handleExport"-->
<!--              v-hasPermi="['system:respinfo:export']"-->
<!--            >导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="respinfoList" @selection-change="handleSelectionChange" @current-change="currentChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="任务名称" align="center" prop="name" />
          <el-table-column label="任务状态" align="center" prop="status" />
          <!-- <el-table-column label="创建人ID" align="center" prop="creater" /> -->
          <!-- <el-table-column label="操作人id" align="center" prop="operter" /> -->
          <el-table-column label="操作时间" align="center" prop="operTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.operTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:respinfo:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:respinfo:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
      <el-col :span="10" style="padding: 85px 0 0;">
        <el-table v-loading="loading" :data="respinfoListDtl">
          <el-table-column label=日期 align="center" width="140" prop="createTime" />
          <el-table-column label="文件" align="center" prop="fileUrl">
            <template slot-scope="scope">
              <div v-for="file in scope.row.fileinfoList"><a :href="file.fileUrl" target="_blank">{{ getFileName(file.fileUrl)[0] }}</a></div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 添加或修改履职任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="安全职责" prop="safeResp">
          <el-input v-model="form.safeResp" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="履职清单" prop="respList">
          <el-input v-model="form.respList" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="履职内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="责任人" prop="respMember">
          <el-select
            v-model="form.respMember"
            placeholder="请选择">
            <el-option
              v-for="item in selectData.respMember"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="执行人" prop="doMemberTmp">
          <el-select
            v-model="form.doMemberTmp"
            multiple
            placeholder="请选择">
            <el-option
              v-for="item in selectData.doMember"
              :key="item.value"
              :label="item.label"
              :value="item.value + ''">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="respDeptName">
          <el-cascader v-model="form.respDeptName" :props="props" :placeholder="form.respDeptname" @change="changeXqid"></el-cascader>
        </el-form-item>
<!--        <el-form-item label="需要完成次数" prop="finishiNum">-->
<!--          <el-input v-model="form.finishiNum" placeholder="请输入需要完成次数" />-->
<!--        </el-form-item>-->
        <el-form-item label="任务类型" prop="job.type">
          <el-radio-group v-model="form.job.type">
            <el-radio :label="1">一次性</el-radio>
            <el-radio :label="2">重复执行</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.job.type === 2" label="执行频率" prop="job.rate">
          <el-radio-group v-model="form.job.rate">
<!--            <el-radio :label="1">每天</el-radio>-->
            <el-radio :label="2">每周</el-radio>
            <el-radio :label="3">每月</el-radio>
            <el-radio :label="4">每年</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.job.type === 2 && form.job.rate === 2" label="周几" prop="job.weekTmp">
          <el-checkbox-group v-model="form.job.weekTmp">
            <el-checkbox v-for="(item, index) in dict.type.sys_week" :key="index" :label="item.value">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="form.job.type === 2 && form.job.rate === 3" label="几号" prop="job.daynoTmp">
          <el-checkbox-group v-model="form.job.daynoTmp">
            <el-checkbox v-for="item in 31" :key="item" :label="item + ''">{{ item }}日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="form.job.type === 2 && form.job.rate === 4" label="几月" prop="job.monthTmp">
          <el-checkbox-group v-model="form.job.monthTmp">
            <el-checkbox v-for="(item, index) in 12" :key="item" :label="item + ''">{{ item + '月' }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="form.job.type === 1" label="执行时间" prop="job.dayTime">
          <el-date-picker
            v-model="form.job.dayTime"
            type="datetime"
            value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="form.job.type === 2 && form.job.rate !== 4" label="执行时间" prop="job.dayTimeTmp">
          <el-time-select
            v-model="form.job.dayTimeTmp"
            :picker-options="{
              start: '08:30',
              step: '00:15',
              end: '23:30'
            }"
            placeholder="选择时间">
          </el-time-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRespinfo, delRespinfo, addRespinfo, updateRespinfo, getUserList, getDetail } from "@/api/system/respinfo";
import { getFileName } from '@/utils'
import {getdeptByparentid} from "@/api/system/dept";
import store from '@/store'

export default {
  name: "Respinfo",
  dicts: ['sys_week'],
  data() {
    return {
      getFileName,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 履职任务表格数据
      respinfoList: [],
      respinfoListDtl: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 查询参数
      queryParamsDtl: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {
        name: null,
        safeResp: null,
        respList: null,
        content: null,
        remark: null,
        respMember: null,
        doMember: null,
        job: {
          type: 1,
          weekTmp: [],
          daynoTmp: [],
          monthTmp: []
        }
      },
      props: {
        checkStrictly: true,
        lazy: true,
        lazyLoad (node, resolve) {
          const params = {
            parentid: ['admin', 'adm'].filter(item => store.getters.roles.includes(item)).length ? 200 : store.getters.deptId,
            deptType: '1'
          }
          console.log('node', node, store.getters)
          params.parentid = node.value || (['admin', 'adm'].filter(item => store.getters.roles.includes(item)).length ? 200 : store.getters.deptId)
          const { level } = node;
          getdeptByparentid(params).then(res => {
            const nodes = res.data.map(item => {
              return {
                value: item.deptId,
                label: item.deptName,
                leaf: level >= 1
              }
            })
            resolve(nodes)
          })
        }
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        respMemberTmp: [
          { required: true, message: '请选择责任人', trigger: 'change' }
        ],
        doMemberTmp: [
          { required: true, message: '请选择执行人', trigger: 'change' }
        ],
        respDeptname: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        'job.type': [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        'job.rate': [
          { required: true, message: '请选择执行频率', trigger: 'change' }
        ],
        'job.weekTmp': [
          { required: true, message: '请选择周几', trigger: 'change' }
        ],
        'job.daynoTmp': [
          { required: true, message: '请选择几号', trigger: 'change' }
        ],
        'job.monthTmp': [
          { required: true, message: '请选择几月', trigger: 'change' }
        ],
        'job.dayTime': [
          { required: true, message: '请选择执行时间', trigger: 'change' }
        ],
        'job.dayTimeTmp': [
          { required: true, message: '请选择执行时间', trigger: 'change' }
        ]
      },
      selectData: {
        respMember: [],
        doMember: []
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    changeXqid(v) {
      this.form.respDeptid = v[v.length - 1]
      console.log('v', v, this.form.xqid)
    },
    querySelect() {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    /** 查询履职任务列表 */
    getList() {
      this.loading = true;
      listRespinfo(this.queryParams).then(response => {
        this.respinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: null,
        safeResp: null,
        respList: null,
        content: null,
        remark: null,
        respMember: null,
        doMember: null,
        job: {
          type: 1,
          weekTmp: [],
          daynoTmp: [],
          monthTmp: []
        }
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    currentChange(currentRow, oldCurrentRow) {
      console.log(currentRow)
      const params = {
        id: currentRow.id
      }
      getDetail(params).then(res => {
        this.respinfoListDtl = res.data.fileList
      })
    },
    async queryMember(roleIds, type) {
      const params = {
        roleid: roleIds,
        deptid: store.getters.deptId,
      }
      await getUserList(params).then(res => {
        this.selectData[type] = res.data.map(item => {
          return {
            value: item.user_id,
            label: item.nick_name
          }
        })
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.queryMember('101', 'respMember')
      this.queryMember('102', 'doMember')
      this.reset();
      this.open = true;
      this.title = "添加履职任务";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      await this.queryMember('101', 'respMember')
      await this.queryMember('102', 'doMember')
      this.reset();
      // const id = row.id || this.ids
      const params = {
        id: row.id
      }
      getDetail(params).then(res => {
        this.form = res.data
        this.form.job = {
          ...this.form.job,
          ...{
            weekTmp: [],
            daynoTmp: [],
            monthTmp: []
          }
        }
        if (this.form.doMember) {
          // this.form.doMemberTmp = this.form.doMember.split(',')
          this.$set(this.form, 'doMemberTmp', this.form.doMember.split(','))
        }
        if (this.form.job.week) {
          this.form.job.weekTmp = this.form.job.week.split(',')
        }
        if (this.form.job.dayno) {
          this.form.job.daynoTmp = this.form.job.dayno.split(',')
        }
        if(this.form.job.month) {
          this.form.job.monthTmp = this.form.job.month.split(',')
        }
        if(this.form.job.type === 2 && this.form.job.dayTime) {
          const arr = this.form.job.dayTime.split(' ')
          const time = arr[arr.length - 1]
          const arr1 = time.split(':')
          arr1.pop()
          console.log('arr1', arr1)
          this.form.job.dayTimeTmp = arr1.join(':')
        }
        console.log('form', this.form, this.selectData)
        this.open = true;
        this.title = "修改履职任务";
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log('form', this.form)
      if (this.form.doMemberTmp) {
        this.form.doMember = this.form.doMemberTmp.toString()
      }
      if(this.form.job.weekTmp?.length) {
        this.form.job.week = this.form.job.weekTmp.toString()
      }
      if(this.form.job.daynoTmp?.length) {
        this.form.job.dayno = this.form.job.daynoTmp.toString()
      }
      if(this.form.job.type === 2 && this.form.job.dayTimeTmp) {
        this.form.job.dayTime = '2000-01-01 ' + this.form.job.dayTimeTmp + ':00'
      }
      if(this.form.job.monthTmp?.length) {
        this.form.job.month = this.form.job.monthTmp.toString()
      }
      console.log('this.form', this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRespinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            addRespinfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(111111111, row.id)
      const ids = [row.id] || this.ids;
      console.log(2222222, ids)
      this.$modal.confirm('是否确认删除履职任务编号为"' + ids + '"的数据项？').then(() => {
        return delRespinfo(ids);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        console.log(44444)
        this.getList();
        console.log(55555555)
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/respinfo/export', {
        ...this.queryParams
      }, `respinfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
